package edu.stanford.bmir.protege.web.server.transform.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLObjectProperty;

import edu.stanford.bmir.protege.web.shared.transform.ClassBean;

public class TxtOwl extends OwlUtil {

	public TxtOwl(String path, Map<String, String> pros, IRI projectIRI)
			throws Exception {
		super(path, pros, projectIRI);
	}

	@Override
	protected List<String> getProperty(String path) {
		File file = new File(path);
	 	BufferedReader reader = null;
	 	List<String> list=new ArrayList<String>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            String lastMapKey="";
            while ((tempString = reader.readLine()) != null) {
            	if("".equals(tempString.trim())){continue;}
            	byte[] BOM = new byte[3];
        		BOM[0]=(byte) 0xEF;
        		BOM[1]=(byte) 0xBB;
        		BOM[2]=(byte) 0xBF;
        		String BOMs = new String(BOM,"UTF-8");
        		if(tempString.contains(BOMs)){
        			tempString=tempString.replaceAll(BOMs, "");
        		}
            	 while ((tempString = reader.readLine())!= null&&!tempString.trim().isEmpty()) {
                	String[] str= tempString.split("\t").length==1?tempString.split(" "):tempString.split("\t");
                	if(!tempString.startsWith(" ")&&!tempString.startsWith("\t")){
                		lastMapKey=str[0]; 	                	
 	                	if ( !list.contains( lastMapKey ) ) {
 	                		list.add( lastMapKey );
 	                	}
                	}
            	 }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
		return list;
	}

	@Override
	protected void createClasses() {
		
		List<ClassBean> clst = readTxt();
    	
    	for ( ClassBean tb : clst ) {
    		
    		createClass(tb);
    		
    	}
		
	}
	
	private OWLClass createClass ( ClassBean tb ) {
		
		String name = tb.getName();
		
		//String pName = tb.getParentName();
		
		OWLClass cls = null;
		
		Map<String,ArrayList> pros = tb.getProperty();
		
		//新txt创建class
		
		List<String> parentPros = getProName(StringWord.SUBCLASSOF);
		
		if ( parentPros.isEmpty() ) {
			
			cls = createClass ( name,null );
			
		} else {
			
			List<String> pNames = pros.get( parentPros.get(0) );
			if ( pNames != null && !pNames.isEmpty() ) {
				
				for ( String pName : pNames ) {
					
					cls =	createClass ( name,pName );
				}
				
			} else {
				cls = createClass ( name,null );
			}
		}
		
		//UF
		/*String pValue = this.pros.get( StringWord.UF );
		if ( pValue != null && pValue != "" ) {
			
			List<String> sNames = pros.get( StringWord.UF );
			
			if ( pValue.equals(StringWord.LABEL) && sNames != null ) {
				
				for ( String sName : sNames  ) {
					setLabel( cls.asOWLClass().getIRI() , sName);
				}
				
			}
		
		}*/
		
		//处理Rt
		List<String> rPros = getProName(StringWord.RELATEDTERM);
		
		if ( !rPros.isEmpty() ) {
			
			for ( String rpName : rPros ) {
				
				List<String> sNames = pros.get( rpName );
				
				if ( sNames == null ) {
					continue;
				}
				
				for ( String sName : sNames ) {
					OWLClass nose = factory.getOWLClass( createIRI( sName ) );
					OWLObjectProperty obp = createObjectproperty( name+"_relatedTerm_"+sName , cls, nose);
					
					addObjectproperty( obp,sName,cls );
					
				}
				
			}
			
		}
		
		/**
		 * 处理等价类
		 */
		List<String> ePros = getProName(StringWord.EQUIVALENTCLASS);
		
		if ( !ePros.isEmpty() ) {
			
			for ( String eName : ePros ) {
				
				List<String> sNames = pros.get( eName );
				
				if ( sNames == null ) {
					continue;
				}
				
				for ( String sName : sNames ) {
					addEquivalentClass( cls , sName);
				}
				
			}
			
		}
		/**
		 * 处理label
		 */
		List<String> lPros = getProName(StringWord.LABEL);
		
		if ( !lPros.isEmpty() ) {
			
			for ( String eName : lPros ) {
				
				List<String> sNames = pros.get( eName );
				
				if ( sNames == null ) {
					continue;
				}
				
				for ( String sName : sNames ) {
					setLabel( cls.asOWLClass().getIRI() , sName);
				}
				
			}
			
		}
		
		List<String> dataPros = getProName(StringWord.DATAPROPERTY);
		
		if ( !dataPros.isEmpty() ) {
			
			for ( String dpName : dataPros ) {
				
				List<String> sNames = pros.get( dpName );
				
				if ( sNames == null ) {
					continue;
				}
				
				for ( String sName : sNames ) {
					addDataproperty( dpName,sName,cls );
					
				}
				
			}
			
		}
		//添加对象属性
		List<String> objectPros = getProName(StringWord.OBJECTPROPERTY);
		if ( !objectPros.isEmpty() ) {
			for ( String opName : objectPros ) {
				List<String> sNames = pros.get( opName );
				if ( sNames == null ) {
					continue;
				}
				for ( String sName : sNames ) {
					addObjectproperty( opName,sName,cls );
				}
			}
		}
    	return cls;
    }

	@Override
	protected void createProperty(String key, String value) {
		
		String pValue = pros.get( key );
		if ( StringWord.OBJECTPROPERTY.equals( pValue ) ) {
			createObjectproperty( key );
		}
		if ( StringWord.DATAPROPERTY.equals( pValue ) ) {
			createDataproperty( key );
		}
		
	/*	if ( "UF".equals( key ) ) {
    		
    	} else {
    		if ( StringWord.OBJECTPROPERTY.equals( value ) ) {
        		
    			createObjectproperty( key );
    			
        	} else if ( StringWord.DATAPROPERTY.equals( value ) ) {
        		
        		createDataproperty( key );
        	}
    	}*/
	}
	
	public List<ClassBean> readTxt(){
	 	File file = new File(getPath());
	 	BufferedReader reader = null;
	 	List list=new ArrayList();
        try {
        	FileInputStream fileInputStream = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(fileInputStream,"UTF-8"));
            String tempString = null;
            String lastMapKey="";
            while ((tempString = reader.readLine()) != null) {
            	if("".equals(tempString.trim())){continue;}
            	byte[] BOM = new byte[3];
        		BOM[0]=(byte) 0xEF;
        		BOM[1]=(byte) 0xBB;
        		BOM[2]=(byte) 0xBF;
        		String BOMs = new String(BOM,"UTF-8");
        		if(tempString.contains(BOMs)){
        			tempString=tempString.replaceAll(BOMs, "");
        		}
            	ClassBean tb=new ClassBean();
            	HashMap<String,ArrayList> map=new HashMap<String, ArrayList>();
            	boolean just = false;
               	tb.setName(tempString);
            	 while ((tempString = reader.readLine())!= null&&!tempString.trim().isEmpty()) {
        			ArrayList<String> arrayList=new ArrayList<String>();
                	String[] str= tempString.split("\t").length==1?tempString.split(" "):tempString.split("\t");
                	int length = str[0].length();
                	int indexOf = tempString.indexOf(str[0]);
                	String temp = "";
                	try {
                		temp = tempString.substring(length+indexOf,tempString.length());
                		temp = temp.trim();
					} catch (Exception e) {
						temp = tempString.replaceFirst(str[0], "").trim();
					}
                	arrayList.add(temp);
                	if(!tempString.startsWith(" ")&&!tempString.startsWith("\t")){
                		lastMapKey=str[0]; 	    
                		if("USE".equals(lastMapKey)||"USE+".equals(lastMapKey)){
                			just = true;
                			continue;
                		}
 	                	if(map.get(str[0])!=null){
 	                		map.get(str[0]).add(tempString.replaceFirst(str[0], "").trim());
 	                	}else{
 	                		map.put(str[0], arrayList);
 	                	}
 	                	
                	}else{
                		map.get(lastMapKey).add(tempString.replaceFirst(str[0], "").trim());
                	}
            	 }
            	 if(just) continue;
            	 tb.setProperty(map);
            	 list.add(tb);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
		return list;
	}

}
